/**
 * Copyright (c) 2009-2011, chunquedong(YangJiandong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 
 * History:
 *     2010-05-05  Jed Young  Creation
 */
package chunmap.raster.gmap;

import java.awt.Image;
import java.util.ArrayList;
import java.util.List;

import chunmap.model.crs.proj.Mercator;
import chunmap.model.elem.Envelope;
import chunmap.raster.Tile;

public class StaticDataSource extends GMDataSource {
	
	private static Mercator proj=new Mercator();
	private static Envelope envelope=new Envelope(-180,-80,180,80);
	
	public StaticDataSource(){
		conn=new StaticGMConn();
	}
	
	public StaticDataSource(String key){
		StaticGMConn c=new StaticGMConn();
		c.key=key;
		conn=c;
	}
	
	//瓦片的大小
    public Envelope getEnvelope(Tile tile)
    {
        return code.getEnvelope(tile);
    }
    
    public Image getImage(GMTile tile_)
    {
    	return conn.getImage(tile_);
    }

    //查找要显示的Tile
    public List<GMTile> getTileSet(Envelope envelope, double scale)
    {
    	Envelope fenv=envelope;
    	if(envelope.hasIntersect(StaticDataSource.envelope)){
    		fenv=envelope.intersection(StaticDataSource.envelope);
    	}
    	
    	Envelope env=fenv.transform(proj.getTransform());
		double bi=env.getWidth()/envelope.getWidth();
		double s=scale/bi;
		
        List<GMTile> list= code.getTileSet(env, s);
        List<GMTile> plist=new ArrayList<GMTile>();
        for (GMTile t : list)
        {
        	SGMTile pt=copy(t);
            pt.setDataSource(this);
            plist.add(pt);
        }
        return plist;
    }
    
    private SGMTile copy(GMTile t){
    	SGMTile pt=new SGMTile(t.x,t.y,t.z);
    	if(t.proxy!=null){
    		pt.proxy=copy(t.proxy);
    	}
    	return pt;
    }

    public Envelope getEnvelop()
    {
        return envelope;
    }
    
    public static class SGMTile extends GMTile{
		public SGMTile(int x, int y, int z) {
			super(x, y, z);
		}
		public @Override Envelope getEnvelop()
	    {
	        return super.getEnvelop().transform(proj.getReverseTransform());
	    }
    }
}